from flask import render_template, request, jsonify, redirect, url_for, session
from . import main_bp
from ..utils.stats import record_visit, get_total_visits, get_api_calls

@main_bp.route('/')
@main_bp.route('/login')
def login():
    if session.get('logged_in'):
        return redirect(url_for('main.index'))
    record_visit('login')
    return render_template('login.html')

@main_bp.route('/login', methods=['POST'])
def handle_login():
    username = request.form.get('username')
    password = request.form.get('password')
    
    if username == 'admin' and password == 'admin':
        session['logged_in'] = True
        return jsonify({'success': True})
    return jsonify({'success': False, 'message': '用户名或密码错误'})

@main_bp.route('/index')
def index():
    if not session.get('logged_in'):
        return redirect(url_for('main.login'))
    record_visit('index')
    return render_template('index.html')

@main_bp.route('/welcome')
def welcome():
    record_visit('welcome')
    # 获取统计数据
    stats = {
        'total_visits': get_total_visits(),
        'api_calls': get_api_calls()
    }
    return render_template('welcome.html', stats=stats)

@main_bp.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('main.login')) 